# -*- coding: utf-8 -*-

import json
import re
import urllib

class Video(object):
	"""Contains the information for one Video"""
	def __init__(self,url=False,youtubeData=False):
		super(Video, self).__init__()

		if (youtubeData and url) or (not youtubeData and not url):
			raise Exception("url or youtubeData must be provided")

		if url:
			youtubeData = self.getYoutubeData(url)

		debug = open("debug/file_1","w")
		debug.write(str(youtubeData))
		debug.close()

		self.videoData = self.parseVideoData(youtubeData)
		self.streamMap = self.getStreamMap(self.videoData[u"id"])


	def getYoutubeData(self,url):
		baseApiUrl = "http://gdata.youtube.com/feeds/api/videos/{0}?alt=json"
		print(url)
		videoID = re.findall('(?:\?|&)v=([^&]*)',str(url))[0]
		apiUrl = baseApiUrl.format(videoID)
		tmpVideoDataFile = open(urllib.urlretrieve(apiUrl)[0])
		videoDataJson = tmpVideoDataFile.read()
		tmpVideoDataFile.close()
		youtubeData = json.loads(videoDataJson)[u"entry"]
		return youtubeData


	def getStreamMap(self,videoID):
		seperatorString = chr(0)

		tmpYoutubeHTML = open(urllib.urlretrieve("http://www.youtube.com/watch?v={0}".format(videoID))[0])
		youtubeHTML = tmpYoutubeHTML.read()
		tmpYoutubeHTML.close()

		mapFinder = re.compile(r'"url_encoded_fmt_stream_map": "([^"]+)"')
		rawStreamMap = mapFinder.findall(youtubeHTML)[0]
		unquotedStreamMap = urllib.unquote(rawStreamMap)

		mapSeperator = re.compile((r",([^+])"))
		streamMapWithSepstr = mapSeperator.sub(seperatorString+r"\1",unquotedStreamMap)
		streamMapArray = streamMapWithSepstr.split(seperatorString)

		streamMap = {}

		for i in range(0,len(streamMapArray)):
			valueArray=streamMapArray[i].split(r"\u0026")
			valueDict={}
			for v in valueArray:
				valueFinder = re.compile(r"([^=]+)=(.*)")
				key,value = valueFinder.findall(v)[0]
				valueDict[key] = value
			streamMap[valueDict["quality"]] = valueDict

		return streamMap


	def parseVideoData(self,youtubeData):
		ytThumbnails = youtubeData[u"media$group"][u"media$thumbnail"]
		self.videoData = {
			u"title":youtubeData[u"title"][u"$t"],
			u"uploader":youtubeData[u"author"][0]["name"]["$t"],
			u"id":youtubeData[u"id"]["$t"][-11:],
			u"thumbnails":ytThumbnails
		}
		return self.videoData




class VideoList(object):
	"""Conatins Multiple Video Objects"""
	def __init__(self):
		super(VideoList, self).__init__()
 
		self._list=[]		

	def addVideo(url):
		pass

	def addPlaylist(url):
		pass


if __name__ == '__main__':
	vid = Video(url=ur"http://www.youtube.com/watch?v=rwO0jTtDIX4&list=WL62A9C48791BEF75F")